package de.suur.jarmi.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GZIPCompressor implements Compressor {

	private static final transient Logger log = LoggerFactory
			.getLogger(GZIPCompressor.class);

	@Override
	public byte[] compress(byte[] data) {
		if (data == null) {
			return null;
		}
		try {
			log.trace("Compress: " + data.length + "|"
					+ JarmiUtil.toString(data));
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			GZIPOutputStream gos = new GZIPOutputStream(bos);
			gos.write(data);
			gos.flush();
			gos.close();
			bos.close();
			byte[] result = bos.toByteArray();
			log.trace("Compressed: " + result.length + "|"
					+ JarmiUtil.toString(result));
			return result;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public byte[] decompress(byte[] data) {
		if (data == null) {
			return null;
		}
		try {
			log.trace("Decompress: " + data.length + "|"
					+ JarmiUtil.toString(data));
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ByteArrayInputStream bis = new ByteArrayInputStream(data);
			GZIPInputStream gis = new GZIPInputStream(bis);
			int input;
			while ((input = gis.read()) != -1) {
				bos.write(input);
			}
			bos.close();
			gis.close();
			bis.close();
			byte[] result = bos.toByteArray();
			log.trace("Decompressed: " + result.length + "|"
					+ JarmiUtil.toString(result));
			return result;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
